const fs = require('fs');
const { pool } = require('../../db/index');
const Router = require('koa-router');

const router = new Router();

// 获取作品列表
router.get('/api/allcalligraphers', async (ctx) => {
    try {
        // 执行 SQL 查询，按朝代分组，获取书法家的朝代、id 和 name
        const [rows] = await pool.execute('SELECT dynasty, id, name FROM all_calligraphers ORDER BY dynasty');
        const result = {};

        // 先按朝代分组书法家信息
        rows.forEach(calligrapher => {
            const { dynasty, id, name } = calligrapher;
            if (!result[dynasty]) {
                result[dynasty] = [];
            }
            result[dynasty].push({ id, name });
        });

        // 将分组结果转换为目标数据结构
        const finalResult = Object.keys(result).map(dynasty => ({
            dynastyName: dynasty,
            list: result[dynasty]
        }));

        ctx.body = finalResult;
    } catch (error) {
        console.error('数据库查询出错:', error);
        ctx.status = 500;
        ctx.body = { error: '服务器内部错误' };
    }
});


// 定义通过 id 查询书法家信息的接口
router.get('/api/cal_detail/:id', async (ctx) => {
    try {
        const id = ctx.params.id;
        // 执行 SQL 查询，通过 id 获取书法家的全部信息
        const [rows] = await pool.execute('SELECT * FROM all_calligraphers WHERE id = ?', [id]);

        if (rows.length === 0) {
            ctx.status = 404;
            ctx.body = { error: '未找到该书法家信息' };
        } else {
            ctx.body = rows[0];
        }
    } catch (error) {
        console.error('数据库查询出错:', error);
        ctx.status = 500;
        ctx.body = { error: '服务器内部错误' };
    }
});
module.exports = router;